//
//  TKIMYYKitHelper.m
//  TKApp
//
//  Created by TryHone on 17/1/4.
//  Copyright © 2017年 liubao. All rights reserved.
//

#import "TKIMYYKitHelper.h"
#import "YYText.h"
#import "YYImage.h"


@implementation TKIMYYKitHelper{
    NSDictionary* _ImageData;
    UIColor *_textColor;
}
/**
 *  @author Alan, 17-01-04 13:01:00
 *
 *  @brief 返回单例对象
 *
 *  @return
 */
+(instancetype)shareInstance{
    static TKIMYYKitHelper *instance = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        instance = [[self.class alloc]init];
    });
    return instance;
}

-(instancetype)init{
    self=[super init];
    if (self) {
        NSString *emotionPlist = TKIMSrcName(@"TKIMEmotion.json");
        NSData *data = [NSData dataWithContentsOfFile:emotionPlist];
        NSDictionary *dic = (NSDictionary *)[TKIMDataHelper dataToObject:data];
        _ImageData = dic[@"emotion"];
        
    }
    return  self;
}


-(NSMutableAttributedString *)processCommentContent:(NSString *)text style:(NSDictionary*)dict textColor:(UIColor *)textColor
{
    //转成可变属性字符串
    NSMutableAttributedString * mAttributedString = [[NSMutableAttributedString alloc]init];
    NSDictionary *attri;
    if (dict) {
        attri=dict;
    }else{
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:4];//调整行间距
        [paragraphStyle setParagraphSpacing:4];//调整行间距
        attri = [NSDictionary dictionaryWithObjects:@[[UIFont systemFontOfSize:15],[UIColor clearColor],paragraphStyle] forKeys:@[NSFontAttributeName,NSForegroundColorAttributeName,NSParagraphStyleAttributeName]];
    }
    _textColor = textColor;
    
    [mAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:text attributes:attri]];
    
    //做解析
    [self Http:mAttributedString];
    [self Phone:mAttributedString];
    [self Image:mAttributedString];
    return mAttributedString;
}


/**
 *  @author Alan, 17-01-04 14:01:12
 *
 *  @brief 检测链接
 *
 *  @param mAttributedString
 */
-(void)Http:(NSMutableAttributedString*)mAttributedString{
    //创建匹配正则表达式的类型描述模板
    //    NSString * pattern = @"http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?";
    NSString* pattern=@"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    
    NSError * error;
    NSRegularExpression * regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    //判断
    if (!regularExpression)//如果匹配规则对象为nil
    {
        NSLog(@"正则创建失败！");
        NSLog(@"error = %@",[error localizedDescription]);
    }
    else
    {
        NSArray * resultArray = [regularExpression matchesInString:mAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, mAttributedString.string.length)];
        for (NSInteger i = resultArray.count - 1; i >= 0; i --)
        {
            NSTextCheckingResult * result = resultArray[i];
            [mAttributedString yy_setUnderlineStyle:NSUnderlineStyleSingle range:result.range];
            [mAttributedString yy_setTextHighlightRange:result.range
                                                  color:_textColor
                                        backgroundColor:_textColor
                                              tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                                  if (_delegate && [_delegate respondsToSelector:@selector(clickedOnLink:clickType:)]) {
                                                      NSString* str=text.string;
                                                      NSString* data=[str substringWithRange:range];
                                                      [_delegate clickedOnLink:data clickType:TKIMTextClickType_Url];
                                                      
                                                  }else{
                                                      NSLog(@"点击事件被丢弃");
                                                  }
                                              }];
        }
        
        
    }
    
}

-(void)Phone:(NSMutableAttributedString*)mAttributedString{
    //创建匹配正则表达式的类型描述模板
    NSString * pattern = @"(\\d{3,4}[- ]?\\d{7,8})";
    NSError * error;
    NSRegularExpression * regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    //判断
    if (!regularExpression)//如果匹配规则对象为nil
    {
        NSLog(@"正则创建失败！");
        NSLog(@"error = %@",[error localizedDescription]);
    }
    else
    {
        NSArray * resultArray = [regularExpression matchesInString:mAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, mAttributedString.string.length)];
        for (NSInteger i = resultArray.count - 1; i >= 0; i --)
        {
            NSTextCheckingResult * result = resultArray[i];
            
            NSString * phone = [mAttributedString.string substringWithRange:result.range];
            
            if ([self isMobileNumber:phone]) {
                [mAttributedString yy_setUnderlineStyle:NSUnderlineStyleSingle range:result.range];
                [mAttributedString yy_setTextHighlightRange:result.range
                                                      color:_textColor
                                            backgroundColor:_textColor
                                                  tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                                      if (_delegate && [_delegate respondsToSelector:@selector(clickedOnLink:clickType:)]) {
                                                          NSString* str=text.string;
                                                          NSString* data=[str substringWithRange:range];
                                                          [_delegate clickedOnLink:data clickType:TKIMTextClickType_Phone];
                                                          
                                                      }else{
                                                          NSLog(@"点击事件被丢弃");
                                                      }
                                                  }];
            }
        }
    }
}


/**
 *  @Author lpm, 16-11-10 13:11:40
 *
 *  @brief  正则判断手机号码地址格式
 *
 *  @param mobileNum
 *
 *  @return
 */
-(BOOL)isMobileNumber:(NSString *)mobileNum
{
    //    电信号段:133/153/180/181/189/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170
    
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    return [regextestmobile evaluateWithObject:mobileNum];
}


/**
 *  @author Alan, 17-01-04 14:01:52
 *
 *  @brief 检测图标
 *
 *  @param mAttributedString
 */
-(void)Image:(NSMutableAttributedString*)mAttributedString{
    
    //创建匹配正则表达式的类型描述模板
    NSString * pattern = @"\\[@[a-zA-Z_.0-9\\u4e00-\\u9fa5]+\\]";
    //创建匹配对象
    NSError * error;
    NSRegularExpression * regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    //判断
    if (!regularExpression)//如果匹配规则对象为nil
    {
        NSLog(@"正则创建失败！");
        NSLog(@"error = %@",[error localizedDescription]);
    }
    else
    {
        NSArray * resultArray = [regularExpression matchesInString:mAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, mAttributedString.string.length)];
        //开始遍历 逆序遍历
        for (NSInteger i = resultArray.count - 1; i >= 0; i --)
        {
            //获取检查结果，里面有range
            NSTextCheckingResult * result = resultArray[i];
            NSString * imageName = [mAttributedString.string substringWithRange:result.range];
            if (imageName)
            {
                //获取图片
                UIImage * image = [self getImageWithRangeString:_ImageData[imageName]];//这是个自定义的方法
                if (image != nil)
                {
                    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
                    
                    imageView.frame=CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y, 23, 23);
                    
                    NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:[UIFont systemFontOfSize:16] alignment:YYTextVerticalAlignmentCenter];
                    //开始替换
                    [mAttributedString replaceCharactersInRange:result.range withAttributedString:attachText];
                }
            }
        }
    }
}

//根据rangeString获取plist中的图片
- (UIImage*)getImageWithRangeString:(NSString*)rangeString
{
    NSString* url = [NSString stringWithFormat:@"%@", rangeString];
    NSString* imgUrl = TKIMSrcName(url);
    NSString* str = [[[imgUrl componentsSeparatedByString:@"/"] lastObject] componentsSeparatedByString:@"."][0];
    NSString* x = TKIMSrcName(str);
//    UIImage* image = [UIImage sd_animatedGIFNamed:x];
    NSData *gifData = [NSData dataWithContentsOfFile:imgUrl];
    UIImage *image = [UIImage sd_imageWithGIFData:gifData];
    return image;
}
@end

